 package com.bafa.front.postlogon;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.bafa.exceptions.ErrorException;
import com.bafa.exceptions.UserDoesNotExistException;
import com.bafa.objects.Message;
import com.bafa.objects.User;
import com.bafa.services.AdminServices;
import com.bafa.services.LogonServices;
import com.bafa.services.teams.TeamServices;

public class UpdateTeamDetailsServlet extends PostLogonServlet {

	@Override
	public void doPostLogonEvent(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException,
			ErrorException {
		message = new Message();
		HttpSession session = request.getSession();

		String tel1 = null;
		String tel2 = null;
		if (request.getParameter("contactTel1") != null
				&& !request.getParameter("contactTel1").equals(""))
			tel1 = new String(request.getParameter("contactTel1"));
		if (request.getParameter("contactTel2") != null
				&& !request.getParameter("contactTel2").equals(""))
			tel2 = new String(request.getParameter("contactTel2"));

		int updated = TeamServices.updateTeamDetails(request
				.getParameter("teamId"), request.getParameter("contactName1"),
				request.getParameter("contactName2"), tel1, tel2, request
						.getParameter("contactEmail1"), request
						.getParameter("contactEmail2"), request
						.getParameter("shirtColour"), request
						.getParameter("username"));

		if (request.getParameter("money") != null
				&& !request.getParameter("money").equals("")) {
			AdminServices.updateMoneyOwed(new Integer(request
					.getParameter("teamId")).intValue(), new Double(request
					.getParameter("money")));
		}
		try {
			if (updated == 0) {
				User user = (User) session.getAttribute("LOGGEDON");
				user = LogonServices.logon(user.getUserId());
				user.setMissingFields(true);
				session.removeAttribute("LOGGEDON");
				session.setAttribute("LOGGEDON", user);
				message.addMessage("Details Successfully Updated");
			} else if (updated == 2) {
				message.addError("Username already exists");
			} else if (updated == 1) {
				message.addError("Details have not been updated");
			} else {
				User user = (User) session.getAttribute("LOGGEDON");
				user = LogonServices.logon(user.getUserId());
				user.setMissingFields(true);
				session.removeAttribute("LOGGEDON");
				session.setAttribute("LOGGEDON", user);
			}
		} catch (UserDoesNotExistException e) {
			message.addError("User does not exist");
		}
	}
}
